package com.juntuo.controller;

import com.gargoylesoftware.htmlunit.WebClient;
import com.github.pagehelper.PageInfo;
import com.juntuo.Enums.CertStatus;
import com.juntuo.Enums.InstitutionStatus;
import com.juntuo.entity.Cert;
import com.juntuo.entity.CertCdf;
import com.juntuo.entity.CertRelationship;
import com.juntuo.entity.User;
import com.juntuo.entity.vo.CertResult;
import com.juntuo.service.CdfCertService;
import com.juntuo.service.CertRelationshipService;
import com.juntuo.service.CertService;
import com.juntuo.service.UserService;
import com.juntuo.shiro.ShiroUtil;
import com.juntuo.util.CertificateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * cdf-cert
 */
@Controller
@RequestMapping("/cdf")
public class CdfCertController {

    @Autowired
    private CertService certService;
    @Autowired
    private UserService userService;
    @Autowired
    private CdfCertService cdfCertService;
    @Autowired
    private CertRelationshipService certRelationshipService;
    @RequestMapping("/index/{id}")
    public String toIndex(@PathVariable Integer id,Model model){
        Cert cert=certService.selectByPrimaryKey(id);
        Integer updateFlag=0;
        if(cert.getUpdateTime()==null){
            updateFlag=1;
        }else{
            updateFlag=(new Date().getTime()-cert.getUpdateTime().getTime())>24*60*60*1000?1:0;
        }
        model.addAttribute("cert",cert);
        model.addAttribute("updateFlag",updateFlag);
        return "/cdf/index";
    }

    @RequestMapping("/page")
    @ResponseBody
    public PageInfo<Map<String,Object>> getPageByMainId(int pageNumber, int pageSize, Integer id,String number, @RequestParam(defaultValue = "0") Integer institution, @RequestParam(defaultValue = "-10") Integer valid){


        return cdfCertService.findPagedCertsByMainCertId(pageNumber,pageSize,id,number,institution,valid);
    }

    /**
     * 输入的时候 autocomplete查询使用
     * @param pageNumber
     * @param pageSize
     * @param number
     * @param institution
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public List<String> getPageCDFCerts(@RequestParam(defaultValue = "1")int pageNumber,@RequestParam(defaultValue = "5") int pageSize,String number,Integer institution){

        List<CertCdf> certCdfs=cdfCertService.getPageCDFCerts(pageNumber,pageSize,number,institution);
        if(certCdfs!=null && certCdfs.size()>0){
            List<String> numbers = new ArrayList<>(certCdfs.size());
            for(CertCdf certCdf:certCdfs){
                numbers.add(certCdf.getNumber());
            }
            return numbers;
        }

        return null;
    }

    /**
     * 这里只有新增 没有更新
     * @param number
     * @param institution
     * @param id
     * @return
     */
    @RequestMapping("/save")
    @ResponseBody
    public boolean saveOne(String number,Integer institution,Integer id){
        number = number.replaceAll("\\s*", "").toUpperCase();
        CertCdf certCdf = new CertCdf();
        certCdf.setNumber(number);
        List<CertCdf> certCdfs=cdfCertService.select(certCdf);
        if(certCdfs==null || certCdfs.size()==0){
            CertCdf certCdf1 = new CertCdf();
            certCdf1.setNumber(number);
            certCdf1.setInstitutionCode(institution);
            certCdf1.setInstitutionName(InstitutionStatus.getByStatus(institution).getDesc());
//            certCdf1.setUpdateTime(new Date()); //新增统一不要更新时间
            certCdf1.setCreateTime(new Date());
            certCdf1.setValid(CertStatus.WAITING.getCode());//这里默认为0 暂时不知是有效还是无效
            cdfCertService.insert(certCdf1);
            System.out.println(certCdf);
        }
        List<CertCdf> certCdfs1=cdfCertService.select(certCdf);
        CertRelationship certRelationship = new CertRelationship();
        certRelationship.setFatherCert(id);
        certRelationship.setChildCert(certCdfs1.get(0).getId());
        certRelationship.setCreateTime(new Date());
        certRelationshipService.insert(certRelationship);
        return true;
    }


    @RequestMapping("/delete/{id}")
    @ResponseBody
    public int deleteOne(@PathVariable int id){
       certRelationshipService.deleteByPrimaryKey(id);
        return 1;
    }
    @RequestMapping("/fresh/{id}")
    @ResponseBody
    public int freshOne(@PathVariable int id){
        CertCdf certCdf=cdfCertService.selectByPrimaryKey(id);
        if(certCdf!=null &&(certCdf.getUpdateTime()==null || ((new Date().getTime()-certCdf.getUpdateTime().getTime())>24*60*60*1000))){
            int institutionCode = certCdf.getInstitutionCode();
            WebClient webClient = CertificateUtils.startAClient();
            CertResult result = CertificateUtils.searchByCode(webClient,certCdf.getNumber(),institutionCode);
            certCdf.setValid(result.getResult());
            if(result.getResult()==CertStatus.OK.getCode()){
                if(result.getCompanyName()!=null){
                    certCdf.setHolderName(result.getCompanyName());
                }
                if(result.getProduct()!=null){
                    certCdf.setProducts(result.getProduct());
                }
                if(result.getModel()!=null){
                    certCdf.setModel(result.getModel());
                }
            }
            certCdf.setUpdateTime(new Date());
            cdfCertService.updateByPrimaryKeySelective(certCdf);
            CertificateUtils.detroyWebClient(webClient);
            return 1;
        }
        return 0;
    }



}
